// 在文件顶部添加express导入
const express = require('express');
const http = require('http');  // 添加这一行
const socketIo = require('socket.io');
const MqttConnector = require('../../common/mqtt-connector');
const TemperatureMonitor = require('./modules/temperature-monitor');
const LedMonitor = require('./modules/led-monitor');
const ServoMonitor = require('./modules/servo-monitor');
// 1. 导入模块
const BarometricPressureMonitor = require('./modules/barometric-pressure-monitor');
const cors = require('cors');

// 先创建Express应用
const app = express();
// 正确应用cors中间件
app.use(cors());
// 设置静态文件目录指向frontend
app.use(express.static(__dirname + '/../frontend'));

// 创建HTTP服务器实例
const server = http.createServer(app);

// 使用服务器实例初始化Socket.io
const io = socketIo(server, {
  // 添加CORS配置
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// MQTT broker地址
const BROKER_URL = 'mqtt://192.168.1.21';

// 设备ID（应与设备端匹配）
const DEVICE_ID = 'iot-test-box-001';

// 创建MQTT连接器实例
const mqttConnector = new MqttConnector(BROKER_URL, 'iot-monitor-web');

// 创建监控模块实例
// 创建监控器实例
const temperatureMonitor = new TemperatureMonitor(DEVICE_ID, mqttConnector);
const ledMonitor = new LedMonitor(DEVICE_ID, mqttConnector);
const servoMonitor = new ServoMonitor(DEVICE_ID, mqttConnector);
const barometricPressureMonitor = new BarometricPressureMonitor(DEVICE_ID, mqttConnector);

// 在文件顶部添加设备存储对象
const registeredDevices = {};

// 修改启动函数
async function startWebMonitor() {
  try {
    // 连接到MQTT broker
    await mqttConnector.connect();

    // 初始化监控模块
    await temperatureMonitor.init();
    await ledMonitor.init();
    await servoMonitor.init();
    await barometricPressureMonitor.init();
    console.log('所有监控模块已初始化');

    // 设置全局消息处理
    mqttConnector.onMessage((topic, message) => {
      try {
        // 注意：message 已经在 mqtt-connector 中解析过了
        temperatureMonitor.handleMessage(topic, message);
        ledMonitor.handleMessage(topic, message);
        servoMonitor.handleMessage(topic, message);
        barometricPressureMonitor.handleMessage(topic, message);
      } catch (error) {
        console.error(`处理MQTT消息错误: ${error.message}`);
      }
    });

    // 设置数据更新回调
    temperatureMonitor.onUpdate = (data) => {
      io.emit('temperature_update', data);
    };

    ledMonitor.onUpdate = (data) => {
      io.emit('led_state_update', data);
    };

    servoMonitor.onUpdate = (data) => {
      io.emit('servo_state_update', data);
    };

    // 设置大气压传感器更新回调
    barometricPressureMonitor.onUpdate = (data) => {
      io.emit('barometric_pressure_update', data);
    };
    



    console.log('IoT网页监控端已成功启动');
    console.log('访问 http://localhost:3000 查看监控界面');

    // 启动服务器 - 使用服务器实例
    server.listen(3000, () => {
      console.log('Web服务器运行在 http://localhost:3000');
    });

    // 处理Socket.io连接
    // 在socket连接处理中添加
    io.on('connection', (socket) => {
      console.log('新客户端连接');

      // 发送已注册设备列表
      socket.emit('registered-devices', Object.values(registeredDevices));

      // 添加处理请求初始数据的事件
      socket.on('request-initial-data', async () => {
        try {
          // 获取各设备的当前数据
          const temperatureData = await temperatureMonitor.getCurrentData();
          const ledData = await ledMonitor.getCurrentData();
          const servoData = await servoMonitor.getCurrentData();
          const pressureData = await barometricPressureMonitor.getCurrentData();

          socket.emit('initial_data', {
            temperature: temperatureData,
            led: ledData,
            servo: servoData,
            barometric_pressure: pressureData
          });
        } catch (error) {
          console.error(`获取初始数据错误: ${error.message}`);
        }
      });

      // 处理请求设备列表
      socket.on('request-devices', () => {
        socket.emit('registered-devices', Object.values(registeredDevices));
      });

      // 处理设备注册请求
      socket.on('register-device', (device) => {
        try {
          console.log('收到设备注册请求:', device);

          // 检查设备是否已存在
          if (registeredDevices[device.id]) {
            socket.emit('device-register-failed', {
              message: '设备ID已存在'
            });
            return;
          }

          // 初始化设备状态
          const newDevice = {
            ...device,
            status: 'online',
            data: {}
          };

          // 存储设备
          registeredDevices[device.id] = newDevice;

          // 通知所有客户端
          io.emit('device-registered', newDevice);

          // 回复注册成功
          socket.emit('device-registered', newDevice);

          console.log('设备注册成功:', device.id);
        } catch (error) {
          console.error(`处理设备注册失败: ${error.message}`);
          socket.emit('device-register-failed', {
            message: error.message
          });
        }
      });

      // 处理设备删除请求
      socket.on('delete-device', (device) => {
        try {
          console.log('收到设备删除请求:', device.id);

          // 检查设备是否存在
          if (!registeredDevices[device.id]) {
            socket.emit('device-delete-failed', {
              message: '设备不存在'
            });
            return;
          }

          // 删除设备
          delete registeredDevices[device.id];

          // 通知所有客户端
          io.emit('device-deleted', device.id);

          console.log('设备删除成功:', device.id);
        } catch (error) {
          console.error(`处理设备删除失败: ${error.message}`);
          socket.emit('device-delete-failed', {
            message: error.message
          });
        }
      });

      // 处理LED控制命令
      socket.on('control_led', async (state) => {
        try {
          console.log(`收到LED控制命令: ${state}`);
          await ledMonitor.control(state);
        } catch (error) {
          console.error(`处理LED控制命令失败: ${error.message}`);
        }
      });


      // 处理舵机控制命令
      socket.on('control_servo', async (angle) => {
        try {
          console.log(`收到舵机控制命令: 设置角度为 ${angle} 度`);
          await servoMonitor.setAngle(angle);
        } catch (error) {
          console.error(`处理舵机控制命令失败: ${error.message}`);
        }
      });
    });
  } catch (error) {
    console.error(`启动网页监控端失败: ${error.message}`);
    process.exit(1);
  }
}

// 处理进程终止信号
process.on('SIGINT', async () => {
  console.log('正在关闭网页监控端...');
  await temperatureMonitor.cleanup();
  await ledMonitor.cleanup();
  await servoMonitor.cleanup();
  mqttConnector.disconnect();
  app.close();
  process.exit(0);
});

// 启动网页监控端
startWebMonitor();

